package com.jyy.prefabricated.service.impl;

import com.jyy.prefabricated.dto.StudentQuizDto;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.ExerciseStatusEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.service.CourseCategoryService;
import com.jyy.prefabricated.service.CoursePackageService;
import com.jyy.prefabricated.service.StudentQuizService;
import com.jyy.prefabricated.utils.DateUtils;
import com.jyy.prefabricated.vo.CourseCategoryData;
import com.jyy.prefabricated.vo.CoursePackageQuizVo;
import com.jyy.prefabricated.vo.StudentExerciseQuestionVo;
import com.jyy.prefabricated.vo.StudentQuizVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 学生随堂考管理表(StudentQuiz)表服务实现类
 *
 * @author makejava
 * @since 2021-10-11 13:49:01
 */
@Service("studentQuizService")
public class StudentQuizServiceImpl implements StudentQuizService {
    @Resource
    private StudentQuizMapper studentQuizMapper;

    @Resource
    private CourseCategoryService courseCategoryService;

    @Resource
    private CoursePackageService coursePackageService;

    @Resource
    private CoursePackageMapper coursePackageMapper;

    @Resource
    private QuizRecordMapper quizRecordMapper;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private StudentQuizQuestionMapper studentQuizQuestionMapper;

    @Resource
    private ViewLogMapper viewLogMapper;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    @Resource
    private CourseCategoryExamMapper courseCategoryExamMapper;


    @Resource
    private StudentQuizService studentQuizService;

    @Resource
    private ExamCertificateMapper examCertificateMapper;
    @Resource
    private StudentCertificateMapper studentCertificateMapper;
    @Resource
    private CertificateMapper certificateMapper;

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public StudentQuiz queryById(Integer id) {
        return this.studentQuizMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<StudentQuiz> queryAllByLimit(int offset, int limit) {
        return this.studentQuizMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param dto 实例对象
     * @return 实例对象
     */
    @Override
    public Integer insert(StudentQuizDto dto) {
        StudentQuiz studentQuiz = new StudentQuiz();
        studentQuiz.setStudentId(dto.getStudentId());
        studentQuiz.setCoursePackageId(dto.getCoursePackageId());
        studentQuiz.setStudentQuizStatus(ExerciseStatusEnum.DOING.getValue());
        studentQuizMapper.insert(studentQuiz);
        Integer studentQuizId = studentQuiz.getId();
//        initExercisePaperDetail(dto.getQuestionBankId(), studentExerciseId);
        initQuizPaperDetailByExamPaperId(dto.getCoursePackageId(), studentQuizId);
        return studentQuizId;
    }

    /**
     * 修改数据
     *
     * @param studentQuiz 实例对象
     * @return 实例对象
     */
    @Override
    public StudentQuiz update(StudentQuiz studentQuiz) {
        this.studentQuizMapper.update(studentQuiz);
        return this.queryById(studentQuiz.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.studentQuizMapper.deleteById(id) > 0;
    }


    /**
     * 我的随堂考列表
     *
     * @param dto 主键
     * @return 是否成功
     */
    @Override
    public List<StudentQuizVo> selectMyQuiz(StudentQuizDto dto) {

        List<StudentQuizVo> result = new ArrayList<>();
        //获取所有课程包二级分类id集合
        List<CourseCategoryData> courseCategoryDataList = courseCategoryService.selectTree(0);

        for (CourseCategoryData courseCategoryData : courseCategoryDataList) {
            if (courseCategoryData.getChildren() != null && courseCategoryData.getChildren().size() > 0) {
                for (CourseCategoryData item : courseCategoryData.getChildren()) {
                    StudentQuizVo studentQuizVo = new StudentQuizVo();
                    //该专项二级分类id
                    studentQuizVo.setCategoryId(item.getId());
                    //该专项二级分类名称
                    studentQuizVo.setCategoryName(item.getCategory());
                    //二级分类下包含的课程包总数
                    List<Integer> categoryIds = coursePackageService.selectDeepCategoryIds(item.getId());
                    List<CoursePackage> coursePackageList = coursePackageService.selectDeepByParams(null, null, null, categoryIds, null, null, null, null);

                    if (coursePackageList != null && coursePackageList.size() > 0) {
                        //该专项下包含课程包总数量
                        studentQuizVo.setTotalCount(coursePackageList.size());
                        //该专项总学时
                        studentQuizVo.setTotalClassHours(coursePackageList.stream().mapToInt(CoursePackage::getClassHours).sum());
                        studentQuizVo.setCoursePackageList(coursePackageList);
                    }
                    result.add(studentQuizVo);
                }
            }
        }

        for (StudentQuizVo studentQuizVo : result) {

            List<Integer> ids = studentQuizVo.getCoursePackageList().stream().map(e -> e.getId()).collect(Collectors.toList());
            if (ids != null && ids.size() > 0) {
                List<CoursePackage> purchaseList = coursePackageMapper.selectByStudent(dto.getStudentId(), ids);
                int count = 0;
                if (purchaseList != null && purchaseList.size() > 0) {
                    for (CoursePackage item : purchaseList) {
                        if (whetherOverdue(item.getOrderId())) {
                            count++;
                        }
                    }
                }
                //该专项下已经购买课程包数量
                studentQuizVo.setPurchaseCount(count);
                //该专项下随堂考已完成通过数量 （随堂考进度=passCount/totalCount）
                int passCount = quizRecordMapper.PassQuizCount(dto.getStudentId(), ids);
                studentQuizVo.setPassCount(passCount);
            }

        }

        return result;
    }

    //判断商品（课程包）是否过期
    public Boolean whetherOverdue(Integer orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
        if (orderInfo != null && orderInfo.getPayTime() != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date currdate = format.parse(orderInfo.getPayTime());
                Calendar ca = Calendar.getInstance();
                ca.setTime(currdate);
                if (orderInfo.getBuyType() != null && orderInfo.getBuyTypeNum() != null) {
                    if (orderInfo.getBuyType() == 0) {
                        ca.add(Calendar.YEAR, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 1) {
                        ca.add(Calendar.MONTH, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 2) {
                        ca.add(Calendar.WEEK_OF_YEAR, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 3) {
                        ca.add(Calendar.DATE, orderInfo.getBuyTypeNum());
                    }
                }
                currdate = ca.getTime();
                long now = DateUtils.getUct8NowDate().getTime();
                if (currdate.getTime() < now) {
                    return false;
                }
            } catch (ParseException e) {
            }

        }
        return true;
    }

    @Override
    public List<CoursePackageQuizVo> selectByCategoryIdAndStudentId(Integer studentId, Integer categoryId) {

        List<CoursePackageQuizVo> result = new ArrayList<>();
        List<Integer> categoryIds = coursePackageService.selectDeepCategoryIds(categoryId);
        List<CoursePackage> coursePackageList = coursePackageService.selectDeepByParams(null, null, null, categoryIds, null, null, null, null);
        if (coursePackageList != null) {
            //该二级分类下，学员已经购买的课程包集合(未过期)
            List<CoursePackage> purchaseList = new ArrayList<>();
            List<Integer> ids = coursePackageList.stream().map(e -> e.getId()).collect(Collectors.toList());
            if (ids != null && ids.size() > 0) {
                //学员已经购买的课程包集合
                List<CoursePackage> alllist = coursePackageMapper.selectByStudent(studentId, ids);
                int count = 0;
                if (alllist != null && alllist.size() > 0) {
                    for (CoursePackage item : alllist) {
                        //判断是否过期
                        if (whetherOverdue(item.getOrderId())) {
                            purchaseList.add(item);
                        }
                    }
                }
                if (purchaseList != null && purchaseList.size() > 0) {
                    for (CoursePackage coursePackage : purchaseList) {
                        //没有包含随堂考的课程包不显示
                        if (coursePackage.getAreas() != null && coursePackage.getAreas().size() > 0) {
                            CoursePackageQuizVo coursePackageQuizVo = new CoursePackageQuizVo();
                            BeanUtils.copyProperties(coursePackage, coursePackageQuizVo);

                            //默认设置为未开始
                            coursePackageQuizVo.setStudentQuizStatus(ExerciseStatusEnum.Four.getValue());
                            coursePackageQuizVo.setClassHours(0);

                            List<QuizRecord> quizRecordList = quizRecordMapper.PassQuiz(studentId, coursePackage.getId());
                            //判断是否可以开始随堂考（统计该学员课程包包含的课程是否学完，学完后才能参加随堂考）
                            boolean mark = true;
                            //调用保利威接口判断学员该课程包是否全部学完
                            //查找课程包包含的视频集合
                            List<Course> courseList = coursePackageService.findCourse(coursePackage);
                            for (Course course : courseList) {
                                if (course.getFiles() != null && course.getFiles().size() > 0) {
                                    for (CourseFile courseFile : course.getFiles()) {
                                        ViewLog viewLog = new ViewLog();
                                        viewLog.setSessionId(studentId.toString());
                                        viewLog.setVideoId(courseFile.getPath());
                                        List<ViewLog> viewLogList = viewLogMapper.queryAll(viewLog);
                                        if (viewLogList != null && viewLogList.size() > 0) {
                                            if (viewLogList.get(0).getPlayDuration() + 10 < Integer.valueOf(viewLogList.get(0).getDuration())
                                                    || Integer.valueOf(viewLogList.get(0).getCurrentTimes() + 10) < Integer.valueOf(viewLogList.get(0).getDuration())) {
                                                mark = false;
                                                break;
                                                /*VodQueryViewLogByDayRequest vodQueryViewLogByDayRequest = new VodQueryViewLogByDayRequest();
                                                List<VodQueryViewLogByDayResponse> vodQueryViewLogByDayResponseList = null;
                                                vodQueryViewLogByDayRequest.setDay(new Date())
                                                        .setVideoId(courseFile.getPath())
                                                        .setCategoryId(null)
                                                        .setSessionId(studentId.toString())
                                                        .setViewerId(null);
                                                vodQueryViewLogByDayResponseList = new VodDataStatisticsServiceImpl().queryViewLogByDay(
                                                        vodQueryViewLogByDayRequest);
                                                Assert.assertNotNull(vodQueryViewLogByDayResponseList);
                                                Integer playDuration = 0;
                                                Integer currentTimes = 0;
                                                for (VodQueryViewLogByDayResponse vodQueryViewLogByDayResponse : vodQueryViewLogByDayResponseList) {
                                                    playDuration += vodQueryViewLogByDayResponse.getPlayDuration();
                                                    currentTimes = vodQueryViewLogByDayResponse.getCurrentTimes();
                                                }
                                                playDuration += viewLogList.get(0).getPlayDuration();
                                                if (playDuration + 10 < Integer.valueOf(viewLogList.get(0).getDuration())
                                                        || currentTimes + 10 < Integer.valueOf(viewLogList.get(0).getDuration())) {
                                                    mark = false;
                                                    break;
                                                }*/
                                            }
                                        } else {
                                            mark = false;
                                            break;
                                            /*VodQueryViewLogByDayRequest vodQueryViewLogByDayRequest = new VodQueryViewLogByDayRequest();
                                            List<VodQueryViewLogByDayResponse> vodQueryViewLogByDayResponseList = null;
                                            vodQueryViewLogByDayRequest.setDay(new Date())
                                                    .setVideoId(courseFile.getPath())
                                                    .setCategoryId(null)
                                                    .setSessionId(studentId.toString())
                                                    .setViewerId(null);
                                            vodQueryViewLogByDayResponseList = new VodDataStatisticsServiceImpl().queryViewLogByDay(
                                                    vodQueryViewLogByDayRequest);
                                            Assert.assertNotNull(vodQueryViewLogByDayResponseList);
                                            if (vodQueryViewLogByDayResponseList == null || vodQueryViewLogByDayResponseList.size() <= 0) {
                                                mark = false;
                                                break;
                                            } else {
                                                Integer playDuration = 0;
                                                Integer currentTimes = 0;
                                                for (VodQueryViewLogByDayResponse vodQueryViewLogByDayResponse : vodQueryViewLogByDayResponseList) {
                                                    playDuration += vodQueryViewLogByDayResponse.getPlayDuration();
                                                    currentTimes = vodQueryViewLogByDayResponse.getCurrentTimes();
                                                }
                                                if (playDuration + 10 < Integer.valueOf(vodQueryViewLogByDayResponseList.get(0).getDuration())
                                                        || currentTimes + 10 < Integer.valueOf(vodQueryViewLogByDayResponseList.get(0).getDuration())) {
                                                    mark = false;
                                                    break;
                                                }
                                            }*/

                                        }
                                    }
                                }
                                if (mark == false) {
                                    break;
                                }
                            }
                            if (mark == true) {
                                coursePackageQuizVo.setStudentQuizStatus(ExerciseStatusEnum.DOING.getValue());
                            }
                            //改课程包下的随堂考已经通过
                            if (quizRecordList != null && quizRecordList.size() > 0) {

                                //存在有效随堂考记录
                                for (QuizRecord quizRecord : quizRecordList) {
                                    if (whetherOverdue(quizRecord.getOrderId())) {
                                        coursePackageQuizVo.setStudentQuizStatus(ExerciseStatusEnum.AFTER.getValue());
                                        coursePackageQuizVo.setGrade(quizRecord.getGrade());
                                        coursePackageQuizVo.setClassHours(quizRecord.getClassHours());
                                        break;
                                    }
                                }
                            }
                            result.add(coursePackageQuizVo);
                        }
                    }

                }

            }
        }
        return result;
    }

    @Override
    public List<CoursePackageQuizVo> selectByCoursePackageId(Integer studentId, Integer coursePackageId) {
        List<CoursePackageQuizVo> result = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        ids.add(coursePackageId);
        if (ids != null && ids.size() > 0) {
            List<CoursePackage> purchaseList = coursePackageMapper.selectByStudent(studentId, ids);
            if (purchaseList != null) {
                for (CoursePackage coursePackage : purchaseList) {
                    //没有包含随堂考的课程包不显示
                    if (coursePackage.getAreas() != null && coursePackage.getAreas().size() > 0) {
                        CoursePackageQuizVo coursePackageQuizVo = new CoursePackageQuizVo();
                        BeanUtils.copyProperties(coursePackage, coursePackageQuizVo);
                        //默认设置为未开始
                        coursePackageQuizVo.setStudentQuizStatus(ExerciseStatusEnum.Four.getValue());
                        coursePackageQuizVo.setClassHours(0);

                        List<QuizRecord> quizRecordList = quizRecordMapper.PassQuiz(studentId, coursePackage.getId());
                        //判断是否可以开始随堂考（统计该学员课程包包含的课程是否学完，学完后才能参加随堂考）
                        boolean mark = true;
                        //调用保利威接口判断学员该课程包是否全部学完
                        //查找课程包包含的视频集合
                        List<Course> courseList = coursePackageService.findCourse(coursePackage);
                        for (Course course : courseList) {
                            if (course.getFiles() != null && course.getFiles().size() > 0) {
                                for (CourseFile courseFile : course.getFiles()) {
                                    ViewLog viewLog = new ViewLog();
                                    viewLog.setSessionId(studentId.toString());
                                    viewLog.setVideoId(courseFile.getPath());
                                    List<ViewLog> viewLogList = viewLogMapper.queryAll(viewLog);
                                    if (viewLogList != null && viewLogList.size() > 0) {
                                        if (viewLogList.get(0).getPlayDuration() + 10 < Integer.valueOf(viewLogList.get(0).getDuration())
                                                || Integer.valueOf(viewLogList.get(0).getCurrentTimes() + 10) < Integer.valueOf(viewLogList.get(0).getDuration())) {
                                            mark = false;
                                            break;
                                        }
                                    } else {
                                        mark = false;
                                        break;

                                    }
                                }
                            }
                            if (mark == false) {
                                break;
                            }
                        }
                        if (mark == true) {
                            coursePackageQuizVo.setStudentQuizStatus(1);
                        }
                        //改课程包下的随堂考已经通过
                        if (quizRecordList != null && quizRecordList.size() > 0) {
                            coursePackageQuizVo.setStudentQuizStatus(ExerciseStatusEnum.AFTER.getValue());
                            coursePackageQuizVo.setGrade(quizRecordList.get(0).getGrade());
                            coursePackageQuizVo.setClassHours(quizRecordList.get(0).getClassHours());
                        }
                        result.add(coursePackageQuizVo);
                    }
                }

            }

        }
        return result;
    }

    @Override
    public void finishQuiz(Integer studentQuizId) {


        StudentQuiz studentQuiz = studentQuizMapper.queryById(studentQuizId);
        if (ExerciseStatusEnum.AFTER.getValue().equals(studentQuiz.getStudentQuizStatus())) {
            throw new CustomException("当前随堂考已结束");
        }

        List<StudentExerciseQuestionVo> questions = studentQuizQuestionMapper.selectQuestionVoByStudentQuizId(studentQuizId);
        Double score = 0d;
        for (StudentExerciseQuestionVo question : questions) {
            if (question.getIfRight() != null && question.getIfRight() == true) {
                score += question.getScore();
            }
        }
        CoursePackage coursePackage = coursePackageMapper.selectByPrimaryKey(studentQuiz.getCoursePackageId());
        //添加随堂考记录

        int now = getSecondTimestamp(DateUtils.getUct8NowDate());
        int createTime = getSecondTimestamp(studentQuiz.getCreateTime());
        int useTime = now - createTime;
        QuizRecord quizRecord = new QuizRecord();
        quizRecord.setStudentQuizId(studentQuizId);
        quizRecord.setStudentId(studentQuiz.getStudentId());
        quizRecord.setCoursePackageId(studentQuiz.getCoursePackageId());
        quizRecord.setUseTime(useTime);
        //随堂考通过
        if (score >= coursePackage.getPassGrade()) {
            quizRecord.setClassHours(coursePackage.getClassHours());
            studentQuiz.setStudentQuizStatus(ExerciseStatusEnum.AFTER.getValue());

            //更新过期证书处理
            //获取该课程包对应的二级分类id
            //必须该考试对应的课程包二级分类学时达到要求才能考试
            //通过学生id和考试id查询课程包分类id集合（二级分类）
            Integer categoryId = getSecondCategory(coursePackage.getCategoryId());
            CourseCategoryExam courseCategoryExam = new CourseCategoryExam();
            courseCategoryExam.setCcId(categoryId);
            //获取二级分类下关联的所有考试
            List<CourseCategoryExam> courseCategoryExamList = courseCategoryExamMapper.queryAll(courseCategoryExam);
            if (courseCategoryExamList != null && courseCategoryExamList.size() > 0) {
                //枚举考试
                for (CourseCategoryExam item : courseCategoryExamList) {
                    //查询用户该分类下随堂考详情列表（有效的）
                    List<CoursePackageQuizVo> list = studentQuizService.selectByCategoryIdAndStudentId(studentQuiz.getStudentId(), categoryId);
                    if (list != null && list.size() > 0) {
                        //统计学时
                        Double userClassHours = list.stream().mapToDouble(CoursePackageQuizVo::getClassHours).sum();
                        if (item.getClassHours() == null) {
                            item.setClassHours("0");
                        }
                        //该考试学时已满足要求
                        if (userClassHours >= Double.parseDouble(item.getClassHours())) {
                            //判断该考试对应的证书学员是否已经过期，过期则更新证书
                            ExamCertificate examCertificate = new ExamCertificate();
                            examCertificate.setExId(item.getExId());
                            //该考试关联的证书集合
                            List<ExamCertificate> examCertificateList = examCertificateMapper.queryAll(examCertificate);
                            if (examCertificateList != null && examCertificateList.size() > 0) {
                                List<Integer> certificateIdList = examCertificateList.stream().map(e -> e.getCfId()).collect(Collectors.toList());
                                //枚举证书，判断学生证书是否过期
                                for (Integer certificateId : certificateIdList) {
                                    StudentCertificate studentCertificate = studentCertificateMapper.selectLastByCertificateIdSt(certificateId, studentQuiz.getStudentId());
                                    if (studentCertificate != null) {
                                        //判断证书是否过期
                                        Calendar ca = Calendar.getInstance();
                                        ca.setTime(studentCertificate.getCreateTime());
                                        Certificate certificate = certificateMapper.selectByPrimaryKey(studentCertificate.getCertificateId());
                                        ca.add(Calendar.YEAR, Integer.valueOf(certificate.getTermOfValidity()));
                                        long nowTime = DateUtils.getUct8NowDate().getTime();
                                        //证书已过期更新证书时间
                                        if (ca.getTime().getTime() < nowTime) {
                                            studentCertificate.setCreateTime(DateUtils.getUct8NowDate());
                                            studentCertificateMapper.updateByPrimaryKeySelective(studentCertificate);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else {
            quizRecord.setClassHours(0);
        }
        quizRecord.setGrade(score);

        //查询有效订单id
        //学员已经购买的课程包集合
        List<CoursePackage> alllist = coursePackageMapper.selectByStudentIdAndCoursePackageId(studentQuiz.getStudentId(), coursePackage.getId());
        int count = 0;
        if (alllist != null && alllist.size() > 0) {
            for (CoursePackage item : alllist) {
                //判断是否过期
                if (whetherOverdue(item.getOrderId())) {
                    quizRecord.setOrderId(item.getOrderId());
                    break;
                }
            }
        }
        quizRecordMapper.insert(quizRecord);

        studentQuiz.setUseTime(useTime);
        studentQuizMapper.update(studentQuiz);


    }

    /**
     * 获取精确到秒的时间戳
     *
     * @return
     */
    public static int getSecondTimestamp(Date date) {
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0, length - 3));
        } else {
            return 0;
        }
    }

    /**
     * 获取课程包所属二级分类id
     *
     * @return
     */
    public int getSecondCategory(Integer id) {
        CourseCategory courseCategory = courseCategoryMapper.selectByPrimaryKey(id);
        if (courseCategory.getPid() == 0) {
            return id;
        }
        return getSecondCategory(courseCategory.getPid());
    }

    /**
     * 初始化练习试题
     *
     * @param coursePackageId
     * @param studentQuizId
     */
    public void initQuizPaperDetailByExamPaperId(Integer coursePackageId, Integer studentQuizId) {
        List<StudentQuizQuestion> studentQuizQuestions = new ArrayList<>();

        CoursePackage examPaper = coursePackageMapper.selectByPrimaryKey(coursePackageId);
        List<Question> questionList = new ArrayList<>();
        if (examPaper.getAreas().size() > 0) {
            for (ExamPaperArea examPaperArea : examPaper.getAreas()) {
                //随机出题
                if (examPaperArea.getRules().size() > 0) {
                    if (examPaperArea.getExtractingStatus() == 0) {
                        for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                            List<Question> alllist = questionMapper.selectByParams(examPaperAreaRule.getQuestionBankId(), examPaperAreaRule.getQuestionType(), examPaperAreaRule.getStemType(), null, null, examPaperAreaRule.getDifficulty(), null, null, null);
                            Collections.shuffle(alllist);
                            //选取随机的集合元素
                            List<Question> randomSeries = alllist.subList(0, examPaperAreaRule.getQuestionCount());
                            for (int i = 0; i < examPaperAreaRule.getQuestionCount(); i++) {
                                if (randomSeries != null && i < randomSeries.size()) {
                                    randomSeries.get(i).setGrade(examPaperAreaRule.getGrade());
                                }
                            }
                            questionList.addAll(randomSeries);
                        }
                    } else {
                        for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                            List<Question> alllist = questionMapper.selectByParams(examPaperAreaRule.getQuestionBankId(), examPaperAreaRule.getQuestionType(), examPaperAreaRule.getStemType(), null, null, examPaperAreaRule.getDifficulty(), null, null, null);
                            //选取随机的集合元素
                            List<Question> randomSeries = alllist.subList(0, examPaperAreaRule.getQuestionCount());
                            for (int i = 0; i < examPaperAreaRule.getQuestionCount(); i++) {
                                if (randomSeries != null && i < randomSeries.size()) {
                                    randomSeries.get(i).setGrade(examPaperAreaRule.getGrade());
                                }
                            }
                            questionList.addAll(randomSeries);
                        }
                    }
                }
            }
        }
        int i = 0;
        for (Question question : questionList) {
            i++;
            StudentQuizQuestion studentQuizQuestion = new StudentQuizQuestion();
            studentQuizQuestion.setQuestionId(question.getId());
            studentQuizQuestion.setStudentQuizId(studentQuizId);
            studentQuizQuestion.setScore(question.getGrade());
            studentQuizQuestion.setSort(i);
            studentQuizQuestions.add(studentQuizQuestion);
        }
        studentQuizQuestionMapper.batchInsert(studentQuizQuestions);
    }

}
